//
//  EPCycle.swift
//  EPHome
//
//  Created by liujianlong on 2022/8/8.
//

import UIKit
///banner
@objc protocol EPCycleDelegate{
    func cellOfIndex(_ cell:UICollectionViewCell, _ indexpath:IndexPath)
    func selectedCell(_ indexpath:IndexPath)
}

@objc public class EPCycle: UIView {
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var page: UIPageControl!
    public var timer : DispatchSourceTimer?
    @objc var delegate:EPCycleDelegate?
    
    public override func awakeFromNib() {
        super.awakeFromNib()
        self.backgroundColor = .white
        weak var weakSelf = self
        self.timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        self.timer?.schedule(deadline: .now(), repeating:.seconds(2))
        self.timer?.setEventHandler(handler: {
            weakSelf?.updateTime()
        })
        self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
    }
    
    @objc public var num = 0{
        didSet{
            self.page.currentPage = 0
            self.page.numberOfPages = num
            self.collectionView.reloadData()
            self.timer?.resume()
        }
    }
    
    func updateTime()
    {
        var offsetx = self.collectionView.contentOffset.x
        offsetx += self.collectionView.bounds.size.width
        self.collectionView.setContentOffset(CGPoint(x:offsetx, y: 0), animated: true)
    }
}

//MARK: - UICollectionViewDataSource
extension EPCycle : UICollectionViewDataSource
{
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.num + 2
    }
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        self.delegate?.cellOfIndex(cell, indexPath)
        return cell
    }
    
    
}
//MARK: - UICollectionViewDelegate
extension EPCycle : UICollectionViewDelegate
{
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.delegate?.selectedCell(indexPath)
    }
}

//MARK: - UICollectionViewDelegateFlowLayout
extension EPCycle : UICollectionViewDelegateFlowLayout{
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return self.frame.size
    }
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
    {
        return 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {
        return 0
    }
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return .zero
    }
}


//MARK: - UIScrollViewDelegate
extension EPCycle : UIScrollViewDelegate {
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        if page == 0{///滚动到最左边
            return scrollView.setContentOffset(CGPoint(x:scrollView.bounds.width *  CGFloat(self.num), y:0), animated:false)
        }else if page == self.num + 1{///滚动到最右边
            return scrollView.setContentOffset(CGPoint(x:scrollView.bounds.width, y:0), animated:false)
        }
        self.page.currentPage = page - 1
    }
    
    public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.timer?.suspend()
    }
    
    public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //        let index = scrollView.contentOffset.x / self.frame.width
        //        self.page.currentPage = Int(ceil(index))
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
            self.timer?.resume()
        }
    }
}
